package com.rybbaby.tss.front.tssStudent.service.imp;

import com.google.common.collect.ImmutableMap;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rybbaby.tss.core.utils.DateUtil;
import com.rybbaby.tss.core.utils.SequenceUtil;
import com.rybbaby.tss.core.utils.StringUtils;
import com.rybbaby.tss.core.web.service.imp.BaseServiceImp;
import com.rybbaby.tss.front.tssAppUser.entity.TssAppUser;
import com.rybbaby.tss.front.tssAppUser.service.ITssAppUserService;
import com.rybbaby.tss.front.tssPertainRelation.dao.ITssPertainRelationDao;
import com.rybbaby.tss.front.tssPertainRelation.entity.TssPertainRelation;
import com.rybbaby.tss.front.tssPertainRelation.service.ITssPertainRelationService;
import com.rybbaby.tss.front.tssStudent.dao.ITssStudentDao;
import com.rybbaby.tss.front.tssStudent.entity.TssStudent;
import com.rybbaby.tss.front.tssStudent.service.ITssStudentService;
import com.rybbaby.tss.platform.sysAdminUser.service.ISysAdminUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author 雷春琼
 * @description 客户表数据库操作服务实现
 * @createDate 2017-08-09 下午2:48:34
 */
@Service
@Transactional
public class TssStudentServiceImp extends BaseServiceImp<TssStudent> implements ITssStudentService {
    @Autowired
    private ITssPertainRelationService tssPertainRelationService;
    @Autowired
    private ITssStudentDao dao;

    @Autowired
    private ITssPertainRelationDao pertainRelationDao;
    @Autowired
    private ISysAdminUserService sysAdminUserService;
    @Autowired
    private ITssAppUserService appUserService;

    /**
     * 新增编辑客户
     *
     * @param entity
     * @return
     */
    @Override
    public Boolean saveOrUpdate(String adminUserId, String pertainRelationList, TssStudent entity) throws Exception {
        boolean bool = true;
        try {
            String id = entity.getId();
            Boolean retionBool = true;
            Gson gson = new Gson();
            // SysAdminUser sysAdminUser=this.sysAdminUserService.get(adminUserId);
            //获取客户亲属对象
            List<TssPertainRelation> relationList = gson.fromJson(pertainRelationList, new TypeToken<List<TssPertainRelation>>() {
            }.getType());

            //entity.setListStatus();
            Date birthDate = entity.getBirthdayDate();
            if (birthDate != null) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                double age = DateUtil.differenceYear(sdf.format(entity.getBirthdayDate()), new Timestamp(System.currentTimeMillis()).toString());
                entity.setAge(age);
            } else {
                entity.setAge(0.0);
            }
            if (StringUtils.isNotBlank(id)) {
                //修改客户信息
                TssStudent studentEntity = this.get(id);
                BeanUtils.copyProperties(entity, studentEntity, "createTime", "listStatus", "adminUserId", "isMember", "empAdminUserId", "stuStatus");
                if (StringUtils.isNotBlank(entity.getEmpAdminUserId())) {
                    studentEntity.setEmpAdminUserId(entity.getEmpAdminUserId());
                }
                if (entity.getStuStatus() != null && entity.getStuStatus() != 0) {
                    studentEntity.setStuStatus(entity.getStuStatus());
                }
                if (entity.getListStatus() != null && entity.getListStatus() != 0) {
                    studentEntity.setListStatus(entity.getListStatus());
                }
                studentEntity.setUpdateTime(new java.sql.Timestamp(System.currentTimeMillis()));
                studentEntity.setContactPhone(relationList.get(0).getContactPhone());
                //设置是否已经注册APP端
                String contactPhone = studentEntity.getContactPhone();
                setRegisterAppStatus(studentEntity, contactPhone);
                this.updateEntitiy(studentEntity);
                //删除之前相关亲属信息
                String sql = "delete from tss_pertain_relation where studentId=?";
                this.tssPertainRelationService.executeSql(sql, new Object[]{id});
                //保存亲属信息
                for (TssPertainRelation tssPertainRelation : relationList) {
                    tssPertainRelation.setCreateTime(new java.sql.Timestamp(System.currentTimeMillis()));
                    tssPertainRelation.setVersion(0);
                    tssPertainRelation.setStudentId(id);
                    tssPertainRelation.setId(SequenceUtil.getUpperCaseUUID());
                }
                retionBool = this.tssPertainRelationService.jdbcBatchSave(relationList);
                if (!retionBool) {
                    return false;
                }
            } else {
                //新增客户信息和亲属所属关系
                entity.setCreateTime(new java.sql.Timestamp(System.currentTimeMillis()));
                entity.setUpdateTime(new Timestamp(System.currentTimeMillis()));
                entity.setContactPhone(relationList.get(0).getContactPhone());
                entity.setAdminUserId(adminUserId);
                entity.setQuickMark(SequenceUtil.getUpperCaseUUID());
                //设置是否已经注册APP端
                String contactPhone = entity.getContactPhone();
                setRegisterAppStatus(entity, contactPhone);
                Serializable newId = this.save(entity);
                //保存亲属信息
                for (TssPertainRelation tssPertainRelation : relationList) {
                    tssPertainRelation.setCreateTime(new java.sql.Timestamp(System.currentTimeMillis()));
                    tssPertainRelation.setVersion(0);
                    tssPertainRelation.setStudentId(newId.toString());
                    tssPertainRelation.setId(SequenceUtil.getUpperCaseUUID());
                }
                retionBool = this.tssPertainRelationService.jdbcBatchSave(relationList);
                if (newId != null && retionBool) {
                    return bool;
                } else {
                    return !bool;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return bool;
    }

    private void setRegisterAppStatus(TssStudent entity, String contactPhone) {
        if (StringUtils.isNotBlank(contactPhone)) {
            List<TssAppUser> appUsers = this.appUserService.findByProperty("phoneNum", contactPhone);
            if (appUsers != null && !appUsers.isEmpty()) {
                entity.setRegisterApp(true);
            } else {
                entity.setRegisterApp(false);
            }
        }
    }

    /**
     * 支持批量修改客户状态以及名单状态
     *
     * @param immutableMap
     * @param ids
     * @return
     */
    @Override
    public Integer updateListStatusOrStatusByIds(ImmutableMap immutableMap, String adminUserId, String ids) {
        return dao.updateListStatusOrStatusByIds(immutableMap, adminUserId, ids);
    }

    @Override
    public List<TssStudent> findStudentByName(String name) throws Exception {
        List<TssStudent> studentByName = dao.findStudentByName(name);
        return studentByName;
    }

    @Override
    public Map<String, Object> getStudentDetailById(String id) {
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> studentMap = this.dao.findById(id);
        //查询会员亲属信息
        List<TssPertainRelation> pertainRelationList = pertainRelationDao.findBySql(studentMap.get("id").toString());
        map.putAll(studentMap);
        map.put("pertainRelationList", pertainRelationList);
        return map;
    }

    @Override
    public Integer updateParameterById(Map<String, Object> map, String id) {
        return dao.updateParameterById(map, id);
    }

    public List<Map<String, Object>> findTodayStudentByType(String adminUserIds) {
        return dao.findTodayStudentByType(adminUserIds);
    }

    @Override
    public List<Map<String, Object>> findMonthStudentByType(String adminUserIds) {
        return dao.findMonthStudentByType(adminUserIds);
    }


    /**
     * 导出数据相关方法
     */

    @Override
    public List<TssStudent> getStudentListById(List<String> stuIdList) {

        return dao.getStudentListById(stuIdList);
    }

    @Override
    public List<TssStudent> getAllStudentList() {
        return dao.getAllStudentList();
    }

    @Override
    public List<TssStudent> findStudentByContactPhone(String contactPhone) throws Exception {
        return dao.findStudentByContactPhone(contactPhone);
    }

    @Override
    public Integer updateStudentIsMember(String id) {
        return dao.updateStudentIsMember(id);
    }

    @Override
    public Boolean findBycontractPhone(String contractPhone, String schoolId,String name) {
        Boolean b = true;
        String sql = "select * from tss_student ts left join sys_admin_user sau on sau.id = ts.adminUserId where  ts.contactPhone = ?  and sau.schoolId = ?  and ts.name=? ";
        List<TssStudent> listBySql = null;
        try {
            listBySql = this.findListBySql(sql, new String[]{contractPhone, schoolId,name});
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (listBySql != null && listBySql.size() > 0) {
            b = false;
        }
        return b;
    }

    @Override
    public List<Map<String, Object>> associatedPark(String contactPhone) {
        return dao.associatedPark(contactPhone);
    }

    @Override
    public List<TssStudent> findByQuickMark(String quickMark) throws Exception {
        return dao.findByQuickMark(quickMark);
    }


    @Override
    public List<TssStudent> getStudentsByClassId(String classId) {
        return this.dao.getStudentsByClassId(classId);
    }

    @Override
    public Serializable addBaby(TssAppUser appUser,Integer relation, TssStudent tssStudent) {
        Serializable newStudentId = this.save(tssStudent);
        if (newStudentId != null) {
            TssPertainRelation pertainRelation = new TssPertainRelation();
            pertainRelation.setStudentId(newStudentId.toString());
            pertainRelation.setPatriarchName(appUser.getName());
            pertainRelation.setAffiliationRelation(relation);
            pertainRelation.setPositionType(1);//决策人
            pertainRelation.setContactPhone(appUser.getPhoneNum());
            pertainRelation.setCreateTime(new java.sql.Timestamp(System.currentTimeMillis()));
        }
        return newStudentId;
    }
}
